#include <iostream>
#include <string>
#include <mysql.h>

const std::string host = "127.0.0.1";
const std::string usr = "xkl";
const std::string passwd = "2036116xklsb?";
const std::string db = "scott";
const unsigned int port = 3306;


int main()
{
    // std::cout << "mysql client version: " << mysql_get_client_info() << std::endl;
    MYSQL* my = mysql_init(nullptr);
    if(my == nullptr)
    {
        std::cout << "mysql_init error" << std::endl;
        return 1;
    }

    if(mysql_real_connect(my, host.c_str(), usr.c_str(), passwd.c_str(), db.c_str(), port, nullptr, 0) == nullptr)
    {
        std::cerr << "mysql_real_connect error" << std::endl;
        return 2;
    }
    mysql_set_character_set(my, "utf8");

    std::string sql = "select * from user";
    int n = mysql_query(my, sql.c_str());
    if(n == 0)
    {
        std::cout << "mysql_query success " << n << std::endl;
    }
    else
    {
        std::cerr << "mysql_query error " << n << std::endl;
        return 0;
    }
    // 提取查询结果
    MYSQL_RES* res = mysql_store_result(my);
    int row = mysql_num_rows(res);      // 行数
    int column = mysql_num_fields(res); // 列数
    std::cout << "row: " << row << " column: " << column << std::endl;
    // 提取每一列的信息
    MYSQL_FIELD* fields = mysql_fetch_field(res);
    for(int i = 0; i < column; i++)
    {
        std::cout << fields[i].name << "\t";// 打印列名
    }
    std::cout << std::endl;

    MYSQL_ROW line;
    for(int i = 0; i < row; i++)
    {
        line = mysql_fetch_row(res);
        for(int j = 0; j < column; j++)
            std::cout << line[j] << "\t";
        std::cout << std::endl;
    }
    // 强转
    // while(true)
    // {
    //     std::cout << "MySQL>> ";
    //     std::string sql;
    //     if(!std::getline(std::cin, sql) || sql == "quit")
    //     {
    //         std::cout << "Bye Bye" << std::endl;
    //         break;
    //     }
    //     int n = mysql_query(my, sql.c_str());
    //     if(n == 0)
    //     {
    //         std::cout << sql << " success " << n << std::endl;
    //     }
    //     else
    //     {
    //         std::cout << sql << " fail " << n << std::endl;
    //     }
    // }

    // std::cout << "mysql connect success" << std::endl;
    mysql_free_result(res);
    mysql_close(my);
    return 0;
}
